package com.wwf.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.wwf.io.Resource;
import com.wwf.pojo.Configuration;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

public class XmlConfigBuilder {

    public Configuration parseXmlConfig(InputStream in) throws DocumentException, PropertyVetoException {
        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read(in);
        Element rootElement = document.getRootElement();
        /**
         * 解析configuration
         */
        List<Element> elements = rootElement.selectNodes("//propoerty");
        Properties properties = new Properties();
        for (Element element : elements) {
            String name = element.attributeValue("name");
            String value = element.attributeValue("value");
            properties.put(name,value);
        }
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        comboPooledDataSource.setDriverClass(properties.getProperty("driverClass"));
        comboPooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
        comboPooledDataSource.setUser(properties.getProperty("username"));
        comboPooledDataSource.setPassword(properties.getProperty("password"));
        Configuration configuration = new Configuration();
        configuration.setDataSource(comboPooledDataSource);
        //解析mapper.xml拿到
        List<Element> list = rootElement.selectNodes("//mapper");
        for (Element element : list) {
            String mapperPath = element.attributeValue("resource");
            InputStream resourceAsStream = Resource.getResourceAsStream(mapperPath);
            //todd 解析mapper 并封装给 Configurtion中的List<mappedSatemented>里
            XmlMapperConfigBuilder xmlMapperBuilder = new XmlMapperConfigBuilder(configuration);
            xmlMapperBuilder.parse(resourceAsStream);
        }
        return configuration;
    }
}
